// pages/videoDetails/videoDetails.js
const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
const formatTime = require('../../utils/util.js').formatTime_2;
let myaudio;
let dsq;
Page({

  /**
   * 页面的初始数据
   */
   data: {
    tabIndex: 0,
    show:false,
    detail:null,
    sharepath:'',
    id:'',
    info:null,
    lessonDetail:null,
    userInfo:null,
    ispayend:false,
    isloading:true,
    ispayend:false,
    currentTime:"0:00",
    percentSj:0,
    bof:true,
    playtext:"../../images/bo.png",
    maxV:100
  },
  onReady() {
    this.videoContext = wx.createVideoContext('video')
  },
  bindended(){
    this.setData({
      ispayend:true
    })
  },
  replay(){
    this.videoContext.play()
    this.setData({
      ispayend:false
    })
  },
  //切换内容
  switchTab: function (event) {
    let tabIndex = event.currentTarget.dataset.tab
    this.setData({
      tabIndex
    });
  },
  info(){
    Controller.info().then(res=>{
      if(res.data.baseData){
        this.setData({
          userInfo:res.data.baseData
        })
      }
    })
  },
  formatRichText(html) {
    if(html){
      let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/<table[^>]*>/gi, function(match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;vertical-align:middle;');
        return match;
      });
      // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
      newContent = newContent.replace(/\<img/gi,
        '<img style="max-width:100%;vertical-align:middle;"');
      return newContent;
    }
  },
  getDetail(id){
    Controller.contentdetail({
      contentId:id
    }).then(res=>{
      if(res.code==0){
        let detail = res.data.baseData
        detail.detail = this.formatRichText(detail.detail)
        detail.time = formatTime(detail.createTime,'-')
        this.setData({
          detail
        })
        if(detail.type){
          this.AudioInit()
        }
        this.getLessonDetail(detail.lessonId)
        this.authordetail(detail.authorId)
      }
    })
  },

  getLessonDetail(id){
    Controller.lessondetail({
      lessonId:id
    }).then(res=>{
      if(res.code==0){
        let lessonDetail = res.data.baseData
        lessonDetail.detail = this.formatRichText(lessonDetail.detail)
        this.setData({
          lessonDetail
        })
      }
    })
  },

  //专家详情
  authordetail(id) {
    Controller.authordetail({
      authorId: id
    }).then(res => {
      if (res.code == 0) {
        let info = res.data.baseData
        this.setData({
          info
        })
      }
    })
  },

  //获取缓存里的用户信息
  // getUserInfo(){
  //   let _self = this
  //   wx.getStorage({
  //     key: 'userInfo',
  //     success: function(res) {
  //       console.log(res)
  //       _self.setData({
  //         userInfo:res.data
  //       })
  //     } 
        
  //   })
  // },

  zan(e){
    if(this.data.detail.hasLike==0){
      this.action(1,true)
    }else{
      var that=this;
      wx.showModal({
        title: '提示',
        content: '是否取消点赞',
        success (res) {
          if (res.confirm) {
            that.action(1,false)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  action(type,isbool){
    var data={}
    if(isbool){
      data.rId=this.data.id
      data.type=type  //类型，1是点赞，2是关注，3.浏览,5分享，6发布,7.签到8.观看视频
      data.source=this.data.detail.source  // 主体对象的类型，1是名医内容，2是专家内容，3.养生视频，4养生资讯，5是商城，6食谱，7名医，8专家
      data.contentType=this.data.detail.type  //内容类型，1是文章，2是视频，3是食谱，4.课程，5是商品
      Controller.action(data).then(res=>{
        if(type==1 && isbool){
          wx.showToast({
            title:res.msg
          })
          this.getDetail(this.data.id)
        }
      })
    }else{
      data.actionId=this.data.detail.likeActionId
      Controller.delAction(data).then(res=>{
        if(res.code==0){
          wx.showToast({
            title:"取消成功"
          })
          this.getDetail(this.data.id)
        }
      })
    }
  },

  goPage(){
    wx.switchTab({ url:'/pages/mall/mall'});
  },

  vip(e){
    if(this.data.userInfo.isVip==1){
      return
    }
    wx.navigateTo({
      url:"/pages/Me/vip"
    });
  },
  //支付 1是名医，2是专家，3.养生视频，4养生资讯
  pay() {
    if(app.globalData.isios){
      wx.showToast({
        title:"ios提示不能支付",
        icon:"none"
      })
      return
    }
    wx.navigateTo({
      url:"/pages/mall/order?ordertype=2&id="+this.data.lessonDetail.id+"&type=course&source=课程"
    });
  },

  play(){
    if(!this.data.detail.allowShow){
      wx.showToast({
        title:"您需先购买课程",
        icon: 'none',
      })
      wx.createVideoContext('video', this).pause();
      return
    }
    this.action(8,true)

  },

  showModel(){
    if(this.data.lessonDetail.hasBuy==1){
      wx.showToast({
        title:"您已购买该课程无需再次购买。",
        icon: 'none',
      })
      return
    }
    this.setData({
      show:true
    })
  },

  close(){
    this.setData({
      show:false
    })
  },
  AudioInit(){
    myaudio = wx.createInnerAudioContext(); //音乐播放实例
    myaudio.title = this.data.detail.title;
    myaudio.epname = this.data.detail.authorName;
    myaudio.src = this.data.detail.audioUrl;
    

    myaudio.onCanplay(()=> {
      // 必须。可以当做是初始化时长
      myaudio.duration;
      // 必须。不然也获取不到时长
      setTimeout(() => {
        this.setData({
          maxV:myaudio.duration
        })
      }, 200)
    })


    myaudio.onPlay(() => {
        this.setData({
          bof:false,
          playtext:"../../images/tin.png"
        })
        clearInterval(dsq)
        myaudio.duration
        
        this.setData({
          maxV:myaudio.duration
        })

        dsq=setInterval(()=>{
          
          if(this.data.maxV == 0 ||this.data.maxV == 100){
              this.setData({
                maxV:myaudio.duration
              })
          }

          this.setData({
            currentTime:this.millisToMinutesAndSeconds(myaudio.currentTime*1000),
            percentSj:myaudio.currentTime
          })
        },500)

        
        


        console.log('录音播放中');
        
    })
    myaudio.onStop(() => {
      clearInterval(dsq)

        console.log('录音暂停');
        this.setData({
            bof:true,
            playtext:"../../images/bo.png"
        })

    })
    myaudio.onEnded(() => {
      clearInterval(dsq)

      console.log('录音播放停止');
      this.setData({
          bof:true,
          playtext:"../../images/bo.png",
          maxV:100,
          currentTime:"0:00",
          percentSj:0
      })
    })



  },
  play2(){
    if(this.data.bof){
        clearInterval(dsq)

        myaudio.play();
        this.setData({
          bof:false,
          playtext:"../../images/tin.png"
        })
    }else{
        clearInterval(dsq)
        myaudio.pause();
        this.setData({
          bof:true,
          playtext:"../../images/bo.png"
        })
    }
  },
  press(event){
      clearInterval(dsq)
      myaudio.pause();
      const position=event.detail.value;
      myaudio.seek(position)
      myaudio.play()

  },
  millisToMinutesAndSeconds(millis) {
    var minutes = Math.floor(millis / 60000);
    var seconds = ((millis % 60000) / 1000).toFixed(0);
    return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
  },
  bindended(){
    this.setData({
      ispayend:true
    })
  },
  replay(){
    this.videoContext.play()
    this.setData({
      ispayend:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({
        sharepath:'/pages/videoDetails/videoDetails?id='+options.id,
        id:options.id
      })
    }
    if(options.parentid){
      app.globalData.parentid=options.parentid
    }
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDetail(this.data.id)
    this.info()
    myaudio.pause();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    myaudio.pause();

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.tabIndex==0){
      return
    }
    this.list = this.selectComponent('#list')
    this.list.load()
  },
  onShareAppMessage: function (e) {
    let title = '';
    let imageUrl = '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },
  onShareTimeline: function(res){
    let title = '';
    let imageUrl = '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },
  
})